<?php
// 应用公共文件

//白名单方法
function is_allow(array $allows, $controller = null, $action = null)
{
    $controller = parse_name(isset($controller) ? $controller : \think\facade\Request::controller(), 0, false);
    $action     = parse_name(isset($action) ? $action : \think\facade\Request::action(), 0, false);
    foreach ($allows as $key => $val) {
        $un = in_array('__un__', $val);
        $c  = $key;
        if ($c == $controller) {
            if (($un && !in_array($action, $val)) || (!$un && in_array($action, $val))) return true;
        }
    }
    return false;
}

function validate_regex($value, $param)
{
    if ($param == 'phone' || $param == 'mobile') {
        return validate_phone($value);
    }
    $list  = config('app.regex_pattern');
    $param = !empty($list) && isset($list[$param]) ? $list[$param] : $param;
    return preg_match($param, $value);
}

//验证手机号（支持国外手机号）
function validate_phone($phone)
{
    if (!preg_match('/^\d{5,16}$/', $phone)) return false;
    return true;
}

/**
 * 简化api if接口使用
 * @param $condtion
 * @param $msg
 */
function apiAsserts($condtion, $msg, $code = 1)
{
    if ($condtion === true) {
        throw new \think\Exception($msg, $code);
    }
}

function make_qiniu_key($filename, $config, $uid = 0, $userKey = 'uid')
{
    $queryArr = [$userKey => $uid];
    $queryArr            = array_merge($queryArr, isset($config['vars']) ? $config['vars'] : []);
    $queryArr['uniqid']  = sha1(uniqid() . get_ucode(6, '1aA'));
    $queryArr['uniqid2'] = get_ucode(6, '1aA');
    $queryArr['date']    = date('Y-m-d');
    $root                = config('upload.platform_config.root_path');
    $ext                 = substr($filename, strripos($filename, '.') + 1);
    $name                = substr($filename, 0, 0 - (strlen($ext) + 1));
    $queryArr['ext']     = ltrim($ext, '.');
    $queryArr['name']    = $name;

    $path                = $root . ltrim($config['path'], '/\\');
    $key                 = parse_tpl($path, $queryArr);
    return $key;
}

/**
 * 获取随机码
 * @static
 * @access public
 * @param int $count 需要生成的位数
 * @param string $type 类型，1代表数字，A代表大写字母，a代表小写字母
 * @return string 随机码
 */
function get_ucode($count = 6, $type = '1')
{
    $code = $tmp = '';
    $abc  = 'abcdefghijklmnopqrstuvwxyz';
    $ABC  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $num  = '0123456789';
    if (strstr($type, 'a')) {
        $code .= $abc;
    }
    if (strstr($type, 'A')) {
        $code .= $ABC;
    }
    if (strstr($type, '1')) {
        $code .= $num;
    }
    for ($i = 0; $i < $count; $i++) {
        $index = rand(0, strlen($code) - 1);
        $tmp   .= $code[$index];
    }
    return $tmp;
}

function parse_tpl($name, $data)
{
    $tpls = config('app.text_tpl');
    $tpl  = isset($tpls[$name]) ? $tpls[$name] : $name;
    foreach ($data as $key => $value) {
        $tpl = preg_replace('/\{\$' . $key . '\}/', $value, $tpl);
    }
    $tpl = preg_replace('/\{\$.+\}/U', '', $tpl);
    return $tpl;
}